layui.use(['form', 'table', 'upload', 'element'], () => {
    const form = layui.form;
    const table = layui.table;
    $ = layui.$; //全局的
    const upload = layui.upload;
    const element = layui.element;

    //渲染表格
    table.render({
        elem: '#goods-list',
        url: '/goods/search',
        page: true,
        toolbar: '#toolbar',
        cols: [[
            {type: 'checkbox'},
            {title: 'ID', field: 'id'},
            {
                title: '图片', templet(d) {
                    // 返回所有的图片
                    var html = '';
                    //遍历所有的图片
                    $.each(d.pics, (index, item) => {
                        html += '<img src="/upload/' + item.url + '">'
                    });
                    return html;
                }
            },
            {title: '书籍名', field: 'name'},
            {title: '售价', field: 'price'},
            {title: '标价', field: 'markPrice'},
            {title: '进价', field: 'purchasePrice'},
            {title: '作者', field: 'author'},
            {title: '出版社', field: 'press'},
            {title: '库存', field: 'count'},
            {
                title: '首页推荐', templet(d) {
                    return ['不推荐', '推荐'][d.recom];
                }
            },
            {
                title: '状态', templet(d) {
                    return ['上架', '下架'][d.status];
                }
            },
            {
                title: '分类', templet(d) {
                    return d.category.name;

                }
            },
            {title: '操作', width: 140, toolbar: '#bar'},
        ]],
        parseData(result) {
            return {
                code: result.code,
                msg: result.msg,
                count: result.data ? result.data.total : 0,
                data: result.data ? result.data.list : null,
            }
        }
    });
    //表格的工具事件
    table.on('toolbar(goods-list)', (obj) => {
        if (obj.event == 'add') {
            //打开添加页面
            openAdd();
        }
    })

    //表格的行工具事件
    table.on('tool(goods-list)', (obj) => {
        if (obj.event == 'edit') {
            openEdit(obj.data);
        } else if (obj.event == 'up') {
            //上架
            enable(obj.data);
        } else if (obj.event == 'down') {
            //下架
            disable(obj.data);
        }
    });

    //禁用
    function disable(goods) {
        layer.confirm('确定要下架当前商品吗？', function (index) {
            layer.close(index);
            edit({id: goods.id, status: 1});
        })

    }

    //启用
    function enable(goods) {
        layer.confirm('确定要上架当前商品吗？', function (index) {
            layer.close(index);
            edit({id: goods.id, status: 0});
        })
    }




    //搜索表格
    form.on('submit(search)', function (data) {
        //刷新表格
        table.reloadData('goods-list', {
            where: data.field,
            page: {curr: 1},
        });

        //阻止表单自动提交
        return false;
    })

    // 一级分类被选中
    form.on('select(parentCategory)', function (data) {
        if (data.value) {
            //选中某个一级分类  加载二级分类
            loadSecondCategory(data.value);
        } else {
            //没选择任何一级分类
            $('select[name="categoryId"]').html('');
            form.render();
        }
    });

    //图片点击删除
    $('.layui-upload-list').on('click', 'div', function () {
        $(this).remove();
    });

    //添加按钮
    form.on('submit(add)', function (data) {
        //ajax
        $.ajax({
            url: '/goods/add',
            data: $(data.form).serialize(),
            type: 'post',
            dataType: 'json',
            success(result) {
                if (result.code == 0) {
                    parent.layer.msg('商品录入成功', {icon: 6});
                    parent.layer.closeAll('iframe');
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            },
            error() {
                layer.msg('请求失败', {icon: 5});
            }
        });
        return false;
    });

    //编辑按钮
    form.on('submit(edit)', function (data) {
        //ajax
        $.ajax({
            url: '/goods/edit',
            data: $(data.form).serialize(),
            type: 'post',
            dataType: 'json',
            success(result) {
                if (result.code == 0) {
                    parent.layer.msg('商品编辑成功', {icon: 6});
                    parent.layer.closeAll('iframe');
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            },
            error() {
                layer.msg('请求失败', {icon: 5});
            }
        });
        return false;
    });

    //图片上传的组件
    // 多图片上传
    upload.render({
        elem: '#ID-upload-demo-btn-2',
        url: '/upload', // 实际使用时改成您自己的上传接口即可。
        multiple: true,
        done: function (res) {
            // 上传完毕
            $('#upload-demo-preview').append('<div><img src="/upload/' + res.data + '"><input type="hidden" name="pic" value="' + res.data + '"></div>')
        }
    });

    //加载一级分类
    loadFirstCategory = function (selectId) {
        //ajax
        $.ajax({
            url: '/category/search',
            data: {parentId: 0},
            dataType: 'json',
            success(result) {
                var html = '<option value="">请选择一级分类</option>'
                $.each(result.data, (index, item) => {
                    if (item.id == selectId) {
                        html += '<option value="' + item.id + '" selected>' + item.name + '</option>'
                    } else {
                        html += '<option value="' + item.id + '">' + item.name + '</option>'
                    }
                });
                $('select[name="parentCategory"]').html(html);
                form.render();
            },
            error() {
                layer.msg('请求失败', {icon: 5});
            }
        });
    }

    //加载二级分类
    loadSecondCategory = function (parentId, selectId) {
        $.ajax({
            url: '/category/search',
            data: {parentId: parentId},
            dataType: 'json',
            success(result) {
                var html = '<option value="">请选择二级分类</option>'
                $.each(result.data, (index, item) => {
                    if (item.id == selectId) {
                        html += '<option value="' + item.id + '" selected>' + item.name + '</option>'
                    } else {
                        html += '<option value="' + item.id + '">' + item.name + '</option>'
                    }
                });
                $('select[name="categoryId"]').html(html);
                form.render();
            },
            error() {
                layer.msg('请求失败', {icon: 5});
            }
        });
    }

    //加载一级分类
    loadFirstCategory();

    //打开添加页面
    function openAdd() {
        //弹出层
        layer.open({
            title: '录入商品信息',
            type: 2,
            area: ['800px', '600px'],
            content: '/html/goods/add.html',

            end() {
                //刷新表格
                table.reloadData("goods-list");
            }
        });
    }

    //打开编辑页面
    function openEdit(goods) {
        console.log(goods);
        layer.open({
            title: '编辑商品信息',
            type: 2,
            area: ['800px', '650px'],
            content: '/html/goods/edit.html',
            success(layero, index, that) {
                // 获取 iframe 的窗口对象
                var iframeWin = window[layero.find('iframe')[0]['name']];
                //使用jQuery，找弹出页面中的元素
                iframeWin.$('input[name="id"]').val(goods.id);
                iframeWin.$('input[name="name"]').val(goods.name);
                iframeWin.$('textarea[name="dscp"]').val(goods.dscp);
                iframeWin.$('input[name="price"]').val(goods.price);
                iframeWin.$('input[name="markPrice"]').val(goods.markPrice);
                iframeWin.$('input[name="purchasePrice"]').val(goods.purchasePrice);
                iframeWin.$('input[name="author"]').val(goods.author);
                iframeWin.$('input[name="press"]').val(goods.press);
                iframeWin.$('input[name="count"]').val(goods.count);
                iframeWin.$('input[name="recom"][value="' + goods.recom + '"]').attr('checked', 'checked');

                //回显一级分类
                iframeWin.loadFirstCategory(goods.category.parentId);
                //回显二级分类
                iframeWin.loadSecondCategory(goods.category.parentId, goods.categoryId);

                //图片的回显
                $.each(goods.pics, (index, item) => {
                    iframeWin.$('#upload-demo-preview').append('<div><img src="/upload/' + item.url + '"><input type="hidden" name="pic" value="' + item.url + '"></div>')
                });
            },
            end() {
                //刷新表格
                table.reloadData("goods-list");
            }
        });
    }

    function edit(goods) {
        $.ajax({
           url: '/goods/edit',
           data: goods,
           type: 'post',
           dataType: 'json',
            success(result) {
                if (result.code == 0) {
                    layer.msg('操作成功！', {icon: 6});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
                //刷新表格
                table.reloadData('goods-list');
            },
            error() {
                layer.msg('请求失败', {icon: 5});
            }
        });
    }
});